'''
 # @ Author: Angyi
 # @ Create Time: 2020-11-13 14:45:01
 # @ Modified by: angyi
 # @ Modified time: 2020-11-18 09:44:23
 # @ Description: 将算法得出的json文件转化为语义分割任务所需要的类别标签，按照输入ssh的分辨率0.25
 '''

import json
import numpy as np 
# data = json.loads('eddytrack.json')
def json_to_img(json_file,lat,lon):
    with open(json_file,'r',encoding='utf8')as fp:
        json_data = json.load(fp)

    # for eddy_list in json_data['data']['lstEddies']:# 对于每个圈圈
    #     print(eddy_list['shapeLats'])

    def fill_in(background):
        # 填充
        for i in range(background.shape[0]):
            point_s = []
            for j in range(background.shape[1]):
                if background[i,j]>0:
                    point_s.append(j)
            if len(point_s)>0:
                background[i,point_s[0]:point_s[-1]] = background[i,point_s[0]]

        return background
    
    # 标记框框
    backg_list = []
    for i,eddy_list in enumerate(json_data['lstEddies']):# 对于1个圈圈

        background = np.zeros((168,168))

        biaoji_x = [np.argmin(np.abs(float(x)-lat)) for x in eddy_list['shapeLats']]
        biaoji_y = [np.argmin(np.abs(float(x)-lon)) for x in eddy_list['shapeLons']]
        background[biaoji_x,biaoji_y] = eddy_list['direction']
        # print( eddy_list['direction'])
        backg_list.append(fill_in(background)) 

    backg = np.array(backg_list).max(axis=0)

    return backg




  

if __name__ == "__main__":
    # file = 'global_allsat/json/nrt_global_allsat_phy_l4_20200101_20200320.json'
    import xarray as xr 
    ssha = xr.open_dataset('../cache/all_year_height.nc')
    lat = ssha.latitude
    lon = ssha.longitude
    # background =  json_to_img(file,lat.data,lon.data)
    # import matplotlib.pyplot as plt 
    # x = np.arange(background.shape[0])
    # y = np.arange(background.shape[1])
    # plt.imshow(background)
    import os 
    json_list = os.listdir('../global_allsat/json')
    json_list.sort(key=lambda x: x.split('_')[-2])
    ground_truth = []
    for file in json_list:
        filepath = '../global_allsat/json/{}'.format(file)
        background =  json_to_img(filepath,lat.data,lon.data)
        ground_truth.append(background)

    ground_truth_array = np.array(ground_truth)
    np.save('ground_truth.npy',ground_truth_array) 
    #ground_truth_array.shape #308 180 140
    ground_truth_test = ground_truth_array[300:,:,:]
    ground_truth_train = ground_truth_array[:300,:,:]
    np.save('../model_data/test/seg_test.npy',ground_truth_test)
    np.save('../model_data/train/seg_train.npy',ground_truth_train)

    # #308 vs 309 json 多一个 怎么肥事
    #  os.listdir('global_allsat\\2020\\')

    # import glob
    # compare_json = []
    # for filename in glob.glob(r'global_allsat\\2020\\*\\*.nc'):
    #     compare_json.append(filename.split('\\')[-1].split('.')[0]+'.json')  
    # t = []
    # for i in json_list:
    #     t.append(i.split('_')[-2])
    #     if i not in compare_json:
    #         print(i)

    # for j,k in enumerate(t):
    #     if k == t[j+1]:
    #         print(j,k)








